from django.shortcuts import render
from django.shortcuts import redirect
from django.http import HttpResponse
from django.template.loader import get_template
from .models import stu_info,all_appoinment,appoinment,record,carTable,time_table,teacher
from django.contrib.auth import authenticate,login as xy_login
from django.contrib.auth import logout
from datetime import date, timedelta, datetime
from django.db.models import Q
import json


# Create your views here.
# 用户登录(管理员端)
def login(request):
    template = get_template('login.html')
    html = template.render({'wrong': '账号或密码错误'})
    if(request.method == 'POST'):
        recv_user = request.POST['user']
        recv_pwd = request.POST['pwd']
        user = authenticate(username = recv_user, password = recv_pwd)
        if user is not None:
            xy_login(request,user)
            response = redirect("/index")
            try:
                remember = request.POST['remember']
                if remember == 'on':
                    response.set_cookie('user', recv_user, max_age=7 * 24 * 3600)
                    response.set_cookie('pwd', recv_pwd, max_age=7 * 24 * 3600)
            except:
                pass
            return response
        return HttpResponse(html)
    print(request.COOKIES)
    # 若之前记住了密码，则获取
    if 'user' in request.COOKIES:
        # 获取记住的用户名
        recv_user = request.COOKIES['user']
        if 'pwd' in request.COOKIES:
            # 获取记住的密码
            recv_pwd = request.COOKIES['pwd']
            return render(request, 'login.html', {'user': recv_user, 'pwd': recv_pwd, 'checked':'checked'})
    return render(request, 'login.html',)

# 登录首页(管理员端)
def index(request):
    if request.user.is_authenticated:
        items = []
        infos = stu_info.objects.filter(status=2)
        count = 0
        for info in infos:
            count = count + 1
            if info.is_test == True:
                test = "是"
            else:
                test = "否"
            a = {"index": count, "name":info.name, "age":info.age, "phone":info.phone_num, "weixin":info.weixin, "place":info.place,"idCard":info.idcard, "status":test}
            items.append(a)
        return render(request, 'index.html', {'items': items, "Count": '管理员'})
    else:
        return redirect("/")

# 审核界面(管理员端)
def admincheck(request):
    if request.user.is_authenticated:
        items = []
        infos = stu_info.objects.filter(status=1)
        count = 0
        for info in infos:
            count = count + 1
            if info.is_test == True:
                test = "是"
            else:
                test = "否"
            a = {"index": count, "name":info.name, "age":info.age, "phone":info.phone_num, "weixin":info.weixin, "place":info.place,"idCard":info.idcard, "status":test}
            items.append(a)
        return render(request, 'check.html', {'items': items, "Count": '管理员'})
    else:
        return redirect("/")

# 通过审核
def checkpass(request):
    if request.user.is_authenticated:
        recv_weixin = request.GET['weixin']
        stu = stu_info.objects.get(weixin=recv_weixin)
        stu.status = 2
        stu.save()
        return redirect("/admincheck")
    else:
        return redirect("/")

# 跳转至添加用户的页面(管理员端)
def add(request):
    if request.user.is_authenticated:
        return render(request, 'add.html')
    else:
        return redirect("/")

# 跳转到未签到学员界面
def unsign(request):
    if request.user.is_authenticated:
        items = []
        infos = record.objects.filter(is_finish=0)
        count = 0
        for item in infos:
            count = count + 1
            info = stu_info.objects.get(weixin=item.weixin)
            if info.is_test == True:
                test = "是"
            else:
                test = "否"
            section = time_table.objects.get(section_id=item.section_id).section
            a = {"index": count, "name": info.name, "phone": info.phone_num, "weixin": info.weixin,
                 "status": test,'date':item.date, 'time':section, 'carnum':item.car_number}
            items.append(a)
        return render(request, 'unsign.html', {'items': items, "Count": '管理员'})
    else:
        return redirect("/")

# 添加用户(管理员端)
def addinfo(request):
    if request.user.is_authenticated:
        recv_name = request.POST['username']
        recv_age = int(request.POST['age'])
        recv_phone = request.POST['phone']
        recv_weixin = request.POST['weixin']
        recv_idcard = request.POST['idCard']
        recv_place = request.POST['place']
        recv_status = request.POST['status']
        if recv_status == "已约考":
            recv_status = True
        else:
            recv_status = False
        student = stu_info(name=recv_name, age=recv_age, phone_num=recv_phone, place=recv_place, weixin=recv_weixin, is_test=recv_status, idcard=recv_idcard)
        student.save()
        return render(request, 'add.html')
    else:
        return redirect("/")

# 更改用户信息(管理员端)
def change(request):
    if request.user.is_authenticated:
        if request.method == "GET":
            weixin = request.GET["weixin"]
            infos = stu_info.objects.filter(weixin=weixin)
            item = {}
            for info in infos:
                if info.is_test == True:
                    test = "启用"
                else:
                    test = "禁用"
                item = {"name":info.name, "age":info.age, "phone":info.phone_num, "weixin":info.weixin, "place":info.place, "status":test, "idcard":info.idcard}
                break
            return render(request, 'change.html', {'item' : item})
        else:
            weixin = request.POST["weixin"]
            user = stu_info.objects.get(weixin=weixin)
            recv_name = request.POST['username']
            recv_age = int(request.POST['age'])
            recv_phone = request.POST['phone']
            recv_weixin = request.POST['weixin']
            recv_idcard = request.POST['idCard']
            recv_place = request.POST['place']
            recv_status = request.POST['status']
            user.name = recv_name
            user.age = recv_age
            user.phone_num = recv_phone
            user.weixin = recv_weixin
            user.idcard = recv_idcard
            user.place = recv_place
            if recv_status == "启用":
                recv_status = True
            else:
                recv_status = False
            user.is_test = recv_status
            user.save()
            return redirect("/index")

    else:
        return redirect("/")

# 删除用户信息(管理员端)
def delete(request):
    if request.user.is_authenticated:
        weixin = request.GET["weixin"]
        user = stu_info.objects.get(weixin=weixin)
        user.delete()
        return redirect("/index")
    else:
        return redirect("/")

# 登出(管理员端)
def logout(request):
    request.session.flush()
    return redirect("/")


def surplus(request):
    today = all_appoinment.objects.get(date=str(date.today()))
    tomorrow = all_appoinment.objects.get(date=str(date.today() + timedelta(days=+1)))
    today_order = today.order_number
    tomorrow_order = tomorrow.order_number
    info = {"today_order":today_order, "tomorrow_order":tomorrow_order}
    return HttpResponse(json.dumps(info))

# 查询是否为临考学员
def checkspecial(request):
    weixin = request.GET["weixin"]
    info = stu_info.objects.get(weixin=weixin)
    res = {"status":info.is_test,'testtime':str(info.testtime)}
    return HttpResponse(json.dumps(res))


# 返回当前日期的预约情况
def detail(request):
    date = request.GET["date"]
    querys = appoinment.objects.filter(date=date)
    items = []
    for info in querys:
        section = time_table.objects.get(section_id=info.section_id).section
        a={"hour":section, "all_order": 4 - info.all_order, "carOneSurplus":info.carOneSurplus, "carTwoSurplus":info.carTwoSurplus, "isShow":True, "id":info.section_id}
        items.append(a)
    return HttpResponse(json.dumps(items))

# 申请预约，不可选车位
def order(request):
    recv_weixin = request.GET["weixin"]
    recv_date = request.GET["date"]
    recv_section_id = request.GET["sectionid"]
    if recv_section_id[0] == 't':
        recv_section_id = recv_section_id[1]
    items = record.objects.filter(Q(weixin=recv_weixin) & Q(date=recv_date)& Q(is_cancel=False))
    if len(items):
        a = {'res' : 0, 'message': '一天内只能预约一次，请勿重复预约'}
        return HttpResponse(json.dumps(a))
    table = appoinment.objects.filter(Q(date=recv_date) & Q(section_id=recv_section_id))
    table = table[0]
    if table.all_order >= 4:
        a = {'res': 1, 'message': '名额已满，下次赶早哦'}
        return HttpResponse(json.dumps(a))
    is_special = stu_info.objects.get(weixin=recv_weixin).is_test
    if not is_special:
        if 0 <= datetime.now().hour < 6:
            a = {'res': 2, 'message': '只能在6:00-24:00内预约哦'}
            return HttpResponse(json.dumps(a))
    else:
        if table.all_order >= 3:
            a = {'res': 1, 'message': '临考学员名额已满，下次赶早哦'}
            return HttpResponse(json.dumps(a))

    # 查询车牌号
    if is_special:
        print(table.all_order)
        if table.all_order == 0:
            linence = carTable.objects.get(Q(carID=1) & Q(time_ID=recv_section_id))
        else:
            linence = carTable.objects.get(Q(carID=2) & Q(time_ID=recv_section_id))
    else:
        if table.all_order < 3:
            linence = carTable.objects.get(Q(carID=1) & Q(time_ID=recv_section_id))
        else:
            linence = carTable.objects.get(Q(carID=2) & Q(time_ID=recv_section_id))
    license_num = linence.license_num

    # 修改预约总表和实时预约表
    big_table = all_appoinment.objects.get(date=recv_date)
    if is_special:
        big_table.order_number = big_table.order_number + 2
        table.all_order = table.all_order + 2
    else:
        big_table.order_number = big_table.order_number + 1
        table.all_order = table.all_order + 1

    print("="*30)

    # 修改约车记录表
    print(recv_date)
    recordTable = record(weixin=recv_weixin, section_id=recv_section_id, date=recv_date, car_number=license_num,is_test=is_special)
    print(recordTable.date)
    big_table.save()
    table.save()
    recordTable.save()
    a = {'res': 3, 'message': '预约成功'}
    return HttpResponse(json.dumps(a))

# 学员签到
def signin(request):
    recv_weixin = request.GET["weixin"]
    recv_date = request.GET["date"]
    recv_section = request.GET["section"]
    try:
        recv_sectionid = time_table.objects.get(section=recv_section).section_id
        item = record.objects.get(Q(weixin=recv_weixin) & Q(date=recv_date) & Q(section_id=recv_sectionid) & Q(is_cancel=False))
        item.is_finish = True
        item.save()
        info = {'res':1}
    except:
        info = {'res': 0}
    return HttpResponse(json.dumps(info))

# 查询是否有该学员信息
def check(request):
    recv_weixin = request.GET['weixin']
    try:
        info = stu_info.objects.get(weixin=recv_weixin)
        res = info.status
        info = {'res': res}
    except:
        info = {'res': 0}
    return HttpResponse(json.dumps(info))

# 学生端录入信息
def stuinfoadd(request):
    recv_weixin = request.GET['weixin']
    recv_name = request.GET['name']
    recv_age = request.GET['age']
    recv_phone = request.GET['phone']
    recv_id = request.GET['id']
    recv_place = request.GET['place']
    # try:
    newstudent = stu_info(weixin=recv_weixin, name=recv_name, age=recv_age, phone_num=recv_phone,
                          idcard=recv_id, place=recv_place, status=1)
    newstudent.save()
    info = {'res': 1}
    # except:
    #     info = {'res': 0}
    return HttpResponse(json.dumps(info))

# 设置约考状态
def special(request):
    recv_weixin = request.GET['weixin']
    try:
        stu = stu_info.objects.get(weixin=recv_weixin)
        stu.is_test = True
        stu.testtime = str(date.today() + timedelta(days=+7))
        stu.save()
        info = {'res': 1}
    except:
        info = {'res': 0}
    return HttpResponse(json.dumps(info))

# 学生取消练车
def remove(request):
    recv_weixin = request.GET['weixin']
    recv_date = request.GET['date']
    recv_section = request.GET['section']
    try:
        recv_sectionid = time_table.objects.get(section=recv_section).section_id
        # 将record表里的is_cancel设置成真
        item = record.objects.get(Q(weixin=recv_weixin) & Q(date=recv_date) & Q(section_id=recv_sectionid) & Q(is_cancel=False))
        item.is_cancel = True
        # 查出车牌号对应的id
        carid = carTable.objects.get(license_num=item.car_number).carID
        # 将appoinment对应的记录减一
        item_appoinment = appoinment.objects.get(Q(date=recv_date) & Q(section_id=recv_sectionid))
        if not item.is_test:
            item_appoinment.all_order = item_appoinment.all_order - 1
            if carid == 1:
                item_appoinment.carOneSurplus = item_appoinment.carOneSurplus - 1
            else:
                item_appoinment.carTwoSurplus = item_appoinment.carTwoSurplus - 1
        else:
            item_appoinment.all_order = item_appoinment.all_order - 2
            if carid == 1:
                item_appoinment.carOneSurplus = item_appoinment.carOneSurplus - 2
            else:
                item_appoinment.carTwoSurplus = item_appoinment.carTwoSurplus - 2
        # 将all_appoinment对应的记录减一
        item_all = all_appoinment.objects.get(date=recv_date)
        if item.is_test:
            item_all.order_number = item_all.order_number - 2
        else:
            item_all.order_number = item_all.order_number - 1
        item.save()
        item_appoinment.save()
        item_all.save()
        info = [{'res': 1}]
    except:
        info = [{'res': 0}]
    return HttpResponse(json.dumps(info))

# 查看是否约考
# def istest(request):
#     recv_weixin = request.GET["weixin"]
#     stu = stu_info.objects.get(weixin=recv_weixin)
#     info = [{'res': int(stu.is_test),'testtime':stu.testtime}]
#     return HttpResponse(json.dumps(info))

# 查询未完成的学车记录
def unfinish(request):
    recv_weixin = request.GET["weixin"]
    items = record.objects.filter(Q(weixin=recv_weixin) & Q(is_finish=False) & Q(is_cancel=False))
    info = []
    id = 1
    for item in items:
        section = time_table.objects.get(section_id=item.section_id).section
        a = {"date": str(item.date), "section": section, "carNumber": item.car_number, "id":id}
        info.append(a)
        id = id + 1
    return HttpResponse(json.dumps(info))

# 查询已完成的学车记录
def finish(request):
    recv_weixin = request.GET["weixin"]
    items = record.objects.filter(Q(weixin=recv_weixin) & Q(is_finish=True))
    info = []
    id = 1
    for item in items:
        section = time_table.objects.get(section_id=item.section_id).section
        a = {"date": str(item.date), "section": section, "carNumber": item.car_number, "id":id}
        info.append(a)
        id = id + 1
    return HttpResponse(json.dumps(info))

# 查询历史记录
def history(request):
    recv_weixin = request.GET["weixin"]
    items = record.objects.filter(weixin=recv_weixin)
    info=[]
    for item in items:
        section = time_table.objects.get(section_id=item.section_id).section
        a = {"date":str(item.date), "section" : section, "carNumber":item.car_number}
        info.append(a)
    return HttpResponse(json.dumps(info))

# 查询用户信息
def userinfo(request):
    weixin = request.GET.get("weixin")
    userInfo = stu_info.objects.filter(weixin=weixin)
    info = {}
    for user in userInfo:
        info = {"name":user.name, "phone":user.phone_num, "age":user.age, "place":user.place, "process":user.is_test, "idCard":user.idcard}
    return HttpResponse(json.dumps(info))

# 教练端
def infointeacher(request):
    weixin = request.GET.get("weixin")
    carnum = teacher.objects.get(weixin=weixin).hiscar.license_num
    items = record.objects.filter(Q(is_finish=False) & Q(is_cancel=False) & Q(car_number=carnum))
    sectionlist = []
    datelist = []
    # 将日期分组
    for item in items:
        if item.date not in datelist:
            datelist.append(item.date)

    # 将时间段分组
    for date in datelist:
        section = []
        for item in items:
            if date == item.date:
                if item.section_id not in section:
                    section.append(item.section_id)
        sectionlist.append(section)
    res=[]
    for i in range(len(datelist)):
        date = datelist[i]
        for section in sectionlist[i]:
            time = time_table.objects.get(section_id=section).section
            names = items.filter(Q(date=date) & Q(section_id=section))
            # namelist=[]
            for name in names:
                hisname = stu_info.objects.get(weixin=name.weixin).name
                # namelist.append(hisname)
                a = {'date': str(date), 'time': time, 'hisname': hisname}
                res.append(a)
            # a={'date':str(date), 'time':time, 'names':namelist}
            # res.append(a)
    return HttpResponse(json.dumps(res))


# 测试
def test(request):
    tomorrow = date.today() + timedelta(days=+1)
    all_appo = all_appoinment(date=tomorrow)
    all_appo.save()
    return redirect("/")

def test2(request):
    today_one = appoinment(date=date.today(), section_id=1, all_order=0, carOneSurplus=0, carTwoSurplus=0)
    today_two = appoinment(date=date.today(), section_id=2, all_order=0, carOneSurplus=0, carTwoSurplus=0)
    today_three = appoinment(date=date.today(), section_id=3, all_order=0, carOneSurplus=0, carTwoSurplus=0)
    today_four = appoinment(date=date.today(), section_id=4, all_order=0, carOneSurplus=0, carTwoSurplus=0)
    today_five = appoinment(date=date.today(), section_id=5, all_order=0, carOneSurplus=0, carTwoSurplus=0)
    today_six = appoinment(date=date.today(), section_id=6, all_order=0, carOneSurplus=0, carTwoSurplus=0)
    today_seven = appoinment(date=date.today(), section_id=7, all_order=0, carOneSurplus=0, carTwoSurplus=0)
    today_eigth = appoinment(date=date.today(), section_id=8, all_order=0, carOneSurplus=0, carTwoSurplus=0)
    today_one.save()
    today_two.save()
    today_three.save()
    today_four.save()
    today_five.save()
    today_six.save()
    today_seven.save()
    today_eigth.save()
    tomorrow_one = appoinment(date=date.today() + timedelta(days=+1), section_id=1, all_order=0, carOneSurplus=0, carTwoSurplus=0)
    tomorrow_two = appoinment(date=date.today() + timedelta(days=+1), section_id=2, all_order=0, carOneSurplus=0, carTwoSurplus=0)
    tomorrow_three = appoinment(date=date.today() + timedelta(days=+1), section_id=3, all_order=0, carOneSurplus=0, carTwoSurplus=0)
    tomorrow_four = appoinment(date=date.today() + timedelta(days=+1), section_id=4, all_order=0, carOneSurplus=0, carTwoSurplus=0)
    tomorrow_five = appoinment(date=date.today() + timedelta(days=+1), section_id=5, all_order=0, carOneSurplus=0, carTwoSurplus=0)
    tomorrow_six = appoinment(date=date.today() + timedelta(days=+1), section_id=6, all_order=0, carOneSurplus=0, carTwoSurplus=0)
    tomorrow_seven = appoinment(date=date.today() + timedelta(days=+1), section_id=7, all_order=0, carOneSurplus=0, carTwoSurplus=0)
    tomorrow_eight = appoinment(date=date.today() + timedelta(days=+1), section_id=7, all_order=0, carOneSurplus=0, carTwoSurplus=0)
    tomorrow_one.save()
    tomorrow_two.save()
    tomorrow_three.save()
    tomorrow_four.save()
    tomorrow_five.save()
    tomorrow_six.save()
    tomorrow_seven.save()
    tomorrow_eight.save()
    return redirect("/")